﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using PS_WSSDeploy_Package.Application;
using PS_WSSDeploy_Package.Utils;
using PS_WSSDeploy_Package.WdCommand;

namespace PS_WSSDeploy_Package.WSPBuilder
{
    class WSPBuildTask : IWdTask
    {
        //Properties

        private string Arguments { get; set; }
        private string ProjectPath { get; set; }

        private string _wspBuilderPath;
        private string WSPBuilderPath
        {
            get
            {
                if (_wspBuilderPath == null)
                {
                    _wspBuilderPath = string.Format( @"{0}\"
                        , Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
                }
                return _wspBuilderPath;
            }
        }

        //Construction

        public WSPBuildTask(string projectPath, string arguments)
        {
            ProjectPath = projectPath;
            Arguments = arguments;
        }

        //Overrides

        public void TaskExecute()
        {
            try
            {
                // Set up process info.
                var psi = new ProcessStartInfo
                              {
                                  FileName = (WSPBuilderPath + @"wspbuilder.exe"),
                                  Arguments = Arguments,
                                  WorkingDirectory = ProjectPath,
                                  CreateNoWindow = true,
                                  UseShellExecute = false,
                                  RedirectStandardInput = true,
                                  RedirectStandardOutput = true,
                                  RedirectStandardError = true
                              };

                // Create the process.
                var process = new Process {StartInfo = psi};

                // Associate process info with the process.

                // Run the process.
                if (!process.Start())
                {
                    throw new Exception("Unable to start WSPBuilder.exe process.");
                }

                while (!process.HasExited)
                {
                    string text = process.StandardOutput.ReadLine();
                    if (!String.IsNullOrEmpty(text))
                    {
                        DTEManager.Instance.WriteBuildWindow(text);
                    }
                    System.Threading.Thread.Sleep(100);
                }

                DTEManager.Instance.WriteBuildWindow(process.StandardOutput.ReadToEnd());
                ++BaseCmd.ResultCounter.Succeeded;
            }
            catch (Exception ex)
            {
                DTEManager.Instance.WriteBuildWindow(string.Format("Build WSP file '{0}': error: {1}", BaseCmd.WSPFileName, ex.Message));
                ++BaseCmd.ResultCounter.Failed;
            }
        }
    }
}
